package com.etong.citymap.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.StringUtil;
import com.etong.citymap.util.UpdateManager;
import com.etong.citymap.util.log.LogUtil;

/**
 * 系统设置界面
 */
public class SettingActivity extends Activity implements OnClickListener{
	LinearLayout set_back;
	LinearLayout set_save;
	EditText set_ip;
	EditText set_history;
	EditText set_refresh_edit;
	Button set_refresh;
	private UpdateManager mUpdateManager;
	private CityApplication cityApplication;
	private SharedPreferences preferences;
	private EditText expiredDate;
	private Button lic_refresh;
	private String licPath;
	private String licName;
	
	Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			refreshLic();
			Toast.makeText(SettingActivity.this, "更新授权成功！", 0).show();
			return true;

		}
	});
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set);
		preferences = this.getSharedPreferences("data",	Context.MODE_WORLD_READABLE);
		cityApplication = (CityApplication)getApplication();
		init();
	}
	void init(){
		set_refresh_edit=(EditText) findViewById(R.id.set_refresh_edit);
		set_back=(LinearLayout) findViewById(R.id.set_back);
		set_back.setOnClickListener(this);
		set_save=(LinearLayout) findViewById(R.id.set_save);
		set_save.setOnClickListener(this);
		set_ip=(EditText) findViewById(R.id.set_ip);
		set_history=(EditText) findViewById(R.id.set_history);
		set_ip.setText(getip());
		set_refresh_edit.setText(cityApplication.getHTTPRefreshUrl());
		set_history.setText(cityApplication.getHistorySaveTime()+"");
		set_refresh=(Button) findViewById(R.id.set_refresh);
		set_refresh.setOnClickListener(this);
		expiredDate = (EditText) findViewById(R.id.expiredDate);
		lic_refresh = (Button) findViewById(R.id.lic_refresh);
		lic_refresh.setOnClickListener(this);
		licPath = Environment.getExternalStorageDirectory()+this.getResources().getString(R.string.city_license);
		licName = "SuperMap iMobile Trial.slm";
		refreshLic();
	}
	
	private void refreshLic(){
		File f = new File(licPath+"/"+licName);
		if(f.exists()){
			try {
				InputStream instream = new FileInputStream(f); 
				if (instream != null) 
				{
					InputStreamReader inputreader = new InputStreamReader(instream);
					BufferedReader buffreader = new BufferedReader(inputreader);
					String line;
					//分行读取
					while (( line = buffreader.readLine()) != null) {
						if(line.startsWith("ExpiredDate")){
							expiredDate.setText(line.replace("ExpiredDate=", ""));
						}
					}                
					instream.close();
				}
			}
			catch (java.io.FileNotFoundException e) 
			{
				Log.d("TestFile", "The File doesn't not exist.");
			} 
			catch (IOException e) 
			{
				Log.d("TestFile", e.getMessage());
			}
		}else{
			expiredDate.setText("无授权文件");
		}
	}
	
	@Override
	public void onClick(View v) {
		if(set_back==v){
			finish();
		}
		if(v==set_save){
			cityApplication.setHTTPURL(set_ip.getText().toString().trim());
			cityApplication.setHTTPRefreshUrl(set_refresh_edit.getText().toString().trim());
			//Configure.HTTPURL=set_ip.getText().toString();
			//Configure.HTTPRefreshUrl=set_refresh_edit.getText().toString();
			String cache=set_history.getText().toString();
			cityApplication.setHistorySaveTime((StringUtil.IsNotNull(cache)?Integer.valueOf(cache):1));
			savedata();
			finish();
		}
		if(set_refresh==v){
			String path=set_refresh_edit.getText().toString();
			if(StringUtil.IsNotNull(path)){
				try{
					cityApplication.setHTTPURL(path);
					//Configure.HTTPRefreshUrl=path;
					mUpdateManager = new UpdateManager(this,cityApplication);
					mUpdateManager.checkUpdateInfo();
				}catch(Exception e){LogUtil.e(e);
				Toast.makeText(this, "下载出错", Toast.LENGTH_SHORT).show();
				}

			}else{
				Toast.makeText(this, "下载出错", Toast.LENGTH_SHORT).show();
			}


		}
		if(lic_refresh==v){
			new DownFile().start();
		}

	}
	void savedata() {
		Editor editor = preferences.edit();
		editor.putString(MainActivity.HttpShareUrl, cityApplication.getHTTPURL());
		editor.putInt(MainActivity.HistoryShareUrl, cityApplication.getHistorySaveTime());
		editor.putString(MainActivity.HttprefreshUrl, cityApplication.getHTTPRefreshUrl());
		editor.commit();

	}
	private String getip(){
		String result=cityApplication.getHTTPURL();
		return result;
	}
	
	class DownFile extends Thread {   //登陆
		@Override
		public void run() {
			int i = HttpSendData.downFile(cityApplication.getHTTPURL()+"supervisor/ashx/key.txt", licPath, licName);
			if(i==0){
				handler.sendEmptyMessage(1);
			}else{
				Toast.makeText(SettingActivity.this, "更新授权失败！", 0).show();
			}
		}

	}
}
